#include "../cpp-httplib/httplib.h"
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
#include "../include/db_manager.h"
#include "../include/auth_manager.h"
#include "../include/employee_handler.h"
#include "../include/department_handler.h"
#include "../include/salary_handler.h"
#include "../include/attendance_handler.h"
#include "../include/admin_handler.h"

int main() {
    // 数据库配置 - 直接硬编码，不使用config.json
    std::string db_host = "localhost";
    std::string db_name = "salary_system";
    std::string db_user = "root";
    std::string db_password = "123456";
    
    // 服务器配置
    std::string server_host = "0.0.0.0";
    int server_port = 8080;
    
    // 初始化数据库连接
    DBManager& db = DBManager::getInstance();
    if (!db.initialize(db_host, db_name, db_user, db_password)) {
        std::cerr << "数据库初始化失败" << std::endl;
        return 1;
    }
    
    // 创建HTTP服务器
    httplib::Server server;
    
    // 静态文件服务
    server.set_mount_point("/", "../web");
    
    // 根目录重定向到登录页面
    server.Get("/", [](const httplib::Request&, httplib::Response& res) {
        res.set_redirect("login.html");
    });
    
    // 登录接口
    server.Post("/api/login", [](const httplib::Request& req, httplib::Response& res) {
        Json::Value request_data;//存储Json变量
        Json::Reader reader;//从req请求中，解析Json字段
        
        if (!reader.parse(req.body, request_data)) {
            res.status = 400;//解析失败，处理逻辑
            res.set_content("{\"error\": \"无效的JSON格式\"}", "application/json");
            return;
        }
        //从Json中提取参数
        std::string username = request_data.get("username", "").asString();
        std::string password = request_data.get("password", "").asString();
        std::string role = request_data.get("role", "").asString();
        
        //进行身份验证
        AuthManager auth;
        std::string token = auth.authenticate(username, password, role);//进行身份验证，得到一个token
        
        if (!token.empty()) {
            //构建Json对象
            Json::Value response;
            response["success"] = true;
            response["token"] = token;
            response["role"] = role;
            response["message"] = "登录成功";
            //序列化
            Json::FastWriter writer;
            res.set_content(writer.write(response), "application/json");
        } else {
            res.status = 401;
            Json::Value response;
            response["success"] = false;
            response["message"] = "用户名或密码错误";
            
            Json::FastWriter writer;
            res.set_content(writer.write(response), "application/json");
        }
    });
    
    // 员工管理接口
    server.Get("/api/employees/([A-Za-z0-9]+)", [](const httplib::Request& req, httplib::Response& res) {
        EmployeeHandler handler;
        //matches[0]是整个匹配到的字符串，matches[1]是第一个捕获组的内容
        std::string employee_id = req.matches[1];//捕获组内容
        std::string result = handler.getEmployeeById(employee_id);
        res.set_content(result, "application/json");
    });
    
    server.Get("/api/employees", [](const httplib::Request&, httplib::Response& res) {
        EmployeeHandler handler;
        std::string result = handler.getAllEmployees();
        res.set_content(result, "application/json");
    });
    
    server.Post("/api/employees", [](const httplib::Request& req, httplib::Response& res) {
        EmployeeHandler handler;
        std::string result = handler.addEmployee(req.body);
        res.set_content(result, "application/json");
    });
    
    server.Put("/api/employees/([A-Za-z0-9]+)", [](const httplib::Request& req, httplib::Response& res) {
        EmployeeHandler handler;
        std::string employee_id = req.matches[1];
        std::string result = handler.updateEmployee(employee_id, req.body);
        res.set_content(result, "application/json");
    });
    
    server.Delete("/api/employees/([A-Za-z0-9]+)", [](const httplib::Request& req, httplib::Response& res) {
        EmployeeHandler handler;
        std::string employee_id = req.matches[1];
        std::string result = handler.deleteEmployee(employee_id);
        res.set_content(result, "application/json");
    });
    
    // 部门管理接口
    server.Get("/api/departments/([A-Za-z0-9]+)", [](const httplib::Request& req, httplib::Response& res) {
        DepartmentHandler handler;
        std::string dept_id = req.matches[1];
        std::string result = handler.getDepartmentById(dept_id);
        res.set_content(result, "application/json");
    });
    
    server.Get("/api/departments", [](const httplib::Request&, httplib::Response& res) {
        DepartmentHandler handler;
        std::string result = handler.getAllDepartments();
        res.set_content(result, "application/json");
    });
    
    server.Post("/api/departments", [](const httplib::Request& req, httplib::Response& res) {
        DepartmentHandler handler;
        std::string result = handler.addDepartment(req.body);
        res.set_content(result, "application/json");
    });
    
    server.Put("/api/departments/([A-Za-z0-9]+)", [](const httplib::Request& req, httplib::Response& res) {
        DepartmentHandler handler;
        std::string dept_id = req.matches[1];
        std::string result = handler.updateDepartment(dept_id, req.body);
        res.set_content(result, "application/json");
    });
    
    server.Delete("/api/departments/([A-Za-z0-9]+)", [](const httplib::Request& req, httplib::Response& res) {
        DepartmentHandler handler;
        std::string dept_id = req.matches[1];
        std::string result = handler.deleteDepartment(dept_id);
        res.set_content(result, "application/json");
    });
    
    // 工资管理接口
    server.Get("/api/salaries", [](const httplib::Request&, httplib::Response& res) {
        SalaryHandler handler;
        std::string result = handler.getAllSalaries();
        res.set_content(result, "application/json");
    });
    
    server.Post("/api/salaries", [](const httplib::Request& req, httplib::Response& res) {
        SalaryHandler handler;
        std::string result = handler.addSalary(req.body);
        res.set_content(result, "application/json");
    });
    
    server.Put("/api/salaries/(.+)", [](const httplib::Request& req, httplib::Response& res) {
        SalaryHandler handler;
        std::string salary_id = req.matches[1];
        std::string result = handler.updateSalary(salary_id, req.body);
        res.set_content(result, "application/json");
    });
    
    server.Delete("/api/salaries/(.+)", [](const httplib::Request& req, httplib::Response& res) {
        SalaryHandler handler;
        std::string salary_id = req.matches[1];
        std::string result = handler.deleteSalary(salary_id);
        res.set_content(result, "application/json");
    });
    
    // 考勤管理接口
    server.Get("/api/attendance", [](const httplib::Request&, httplib::Response& res) {
        AttendanceHandler handler;
        std::string result = handler.getAllAttendance();
        res.set_content(result, "application/json");
    });
    
    server.Post("/api/attendance", [](const httplib::Request& req, httplib::Response& res) {
        AttendanceHandler handler;
        std::string result = handler.addAttendance(req.body);
        res.set_content(result, "application/json");
    });
    
    server.Put("/api/attendance/(.+)", [](const httplib::Request& req, httplib::Response& res) {
        AttendanceHandler handler;
        std::string attendance_id = req.matches[1];
        std::string result = handler.updateAttendance(attendance_id, req.body);
        res.set_content(result, "application/json");
    });
    
    server.Delete("/api/attendance/(.+)", [](const httplib::Request& req, httplib::Response& res) {
        AttendanceHandler handler;
        std::string attendance_id = req.matches[1];
        std::string result = handler.deleteAttendance(attendance_id);
        res.set_content(result, "application/json");
    });
    
    // 管理员接口
    server.Get("/api/admin/statistics", [](const httplib::Request&, httplib::Response& res) {
        AdminHandler handler;
        std::string result = handler.getSystemStatistics();
        res.set_content(result, "application/json");
    });
    
    server.Get("/api/admin/reports", [](const httplib::Request&, httplib::Response& res) {
        AdminHandler handler;
        std::string result = handler.getSystemReports();
        res.set_content(result, "application/json");
    });
    
    server.Get("/api/admin/system-info", [](const httplib::Request&, httplib::Response& res) {
        AdminHandler handler;
        std::string result = handler.getSystemInfo();
        res.set_content(result, "application/json");
    });
    
    // 启动服务器
    std::cout << "薪资管理系统服务器启动在 http://" << server_host << ":" << server_port << std::endl;
    std::cout << "数据库连接: " << db_host << ":" << db_name << std::endl;
    
    if (!server.listen(server_host.c_str(), server_port)) {
        std::cerr << "服务器启动失败" << std::endl;
        return 1;
    }
    
    return 0;
} 